package _2025_4_27;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoSever {
    ServerSocket socket;
    //定义客户端
    public TCPEchoSever(int pase) throws IOException {
        if(pase<1024||pase>65535){
            System.out.println("端口号不符合条件");
        }
       this.socket=new ServerSocket(pase);
    }
    public void start() throws IOException {
        System.out.println("服务器已启动，等待客服端连接");
        //循环接收连接需求
        while (true){
            Socket clientsocket=socket.accept();
            //创建一个方法去接收客服端的内容
            reviceports(clientsocket);

        }
    }
    public void reviceports(Socket clientsocket) throws IOException {

        System.out.printf("[%s %d] 客服端上线了\n",clientsocket.getInetAddress().toString(),clientsocket.getPort());
        //使用输出流和输入流进行接收
            try(InputStream inputStream= clientsocket.getInputStream();
                OutputStream outputStream= clientsocket.getOutputStream()){
                while (true) {
                    Scanner scanner = new Scanner(inputStream);//嵌入输入流
                    if (!scanner.hasNextLine()) {
                        System.out.printf("[%s %d] 客服端下线了",clientsocket.getInetAddress().toString(),clientsocket.getPort());
                        break;
                    }
                    //获取用户发来的内容
                    String request = scanner.nextLine();
                    //对内容进行计算响应
                    String respose = Calculation(request);
                    //把响应写入输出流
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(respose);
                    //刷新缓冲区
                    printWriter.flush();
                    //打印
                    System.out.printf("[%s:%d] request=%s,respose=%s\n", clientsocket.getInetAddress().toString(), clientsocket.getPort(), request, respose);
                }
            }
    }
    protected String Calculation(String respose){
        return respose;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSever tcpEchoSever=new TCPEchoSever(8888);
        tcpEchoSever.start();
    }
}
